<template>
  <div class="canvasFingerTouch">
    <canvas id="fingerTouch" ref="fingerTouchRef"
     :width="rect?.width" :height="rect?.height"
     @touchstart="move"
     @touchmove="move"></canvas>
  </div>
</template>

<script lang="ts">
import { Vue, Options } from 'vue-property-decorator';
interface Pos{
  x: number,
  y: number
}
@Options({ components: {

} })
export default class CanvasFingerTouch extends Vue {
  private rect: null |  DOMRect= null;
  private timer: number|null = null;
  private ctx: CanvasRenderingContext2D |null = null;
  private endTo: Pos={ x: 0, y: 0 };
  private current: Pos={ x: 0, y: 0 };

  public move(e: TouchEvent) {
    this.endTo.x = e.touches[0].pageX - this.rect!.x;
    this.endTo.y = e.touches[0].pageY - this.rect!.y;
    console.log(e);
    if (!this.timer) {
      this.play();
    };
  }
  public play() {
    if (Math.abs(this.endTo.x - this.current.x) > 0.1 || Math.abs(this.endTo.y - this.current.y) > 0.1) {
      this.current.x += (this.endTo.x - this.current.x) / 10;
      this.current.y += (this.endTo.y - this.current.y) / 10;
      this.ctx!.clearRect(0, 0, this.ctx!.canvas.width, this.ctx!.canvas.height);
      this.ctx!.save();
      this.ctx!.translate(this.current.x, this.current.y);
      this.ctx!.scale(3, 3);
      // this.ctx!.translate(-15, -15);
      // fillRec的x y是缩放控制点
      this.ctx!.fillRect(-15, -15, 30, 30);
      this.ctx!.restore();
      this.timer = window.requestAnimationFrame(this.play);
    } else {
      this.timer = null;
    }
  }
  public mounted() {
    this.rect = (this.$el as HTMLDivElement).getBoundingClientRect();
    const canvas = this.$refs.fingerTouchRef as HTMLCanvasElement;
    this.ctx = canvas.getContext('2d');
    this.ctx!.fillStyle = 'red';
  }
  public unmounted() {
    window.cancelAnimationFrame(this.timer!);
    this.timer = null;
  }
};
</script>

<style lang="postcss">
.canvasFingerTouch{
  position: relative;
  width: 100%;
  height: 100%;
  touch-action: none;
  #fingerTouch{
    position: absolute;
    left: 0;
    top: 0;
    background-color: #fff;
  }
}

</style>
